import { useCallback, useEffect, useState } from "react"
import {
  FlatList,
  ImageStyle,
  ListRenderItem,
  Pressable,
  TextStyle,
  View,
  ViewStyle,
} from "react-native"
import { Image } from "expo-image"
import { router, useFocusEffect } from "expo-router"
import { formatDistanceToNow } from "date-fns"
import { zhCN } from "date-fns/locale"

import { Button, Screen, Text } from "@/components"
import { useStores } from "@/models/helpers/useStores"
import { getModels } from "@/services/api/agents"
import { ConversationSummary } from "@/services/api/conversations"
import { useAppTheme } from "@/theme/context"
import { $styles } from "@/theme/styles"
import type { ThemedStyle } from "@/theme/types"

interface Conversation {
  id: string
  title: string
  participants: string[]
  lastMessage: string
  updatedAt: string
  unreadCount?: number
  pinned?: boolean
}

interface ConversationRow extends Conversation {
  updatedAtLabel: string
}

const conversationFixtures: Conversation[] = [
  {
    id: "conv-1",
    title: "产品需求梳理",
    participants: ["OctopusGPT", "我"],
    lastMessage: "好的，我会根据最新反馈重新整理需求文档。",
    updatedAt: new Date(Date.now() - 5 * 60 * 1000).toISOString(),
    unreadCount: 2,
    pinned: true,
  },
]

const ConversationsPage = () => {
  const { themed } = useAppTheme()
  const { conversationsStore, agentsStore } = useStores()
  const [conversations, setConversations] = useState<ConversationSummary[]>([])
  const data: ConversationRow[] = conversationFixtures.map((conversation) => ({
    ...conversation,
    updatedAtLabel: formatDistanceToNow(new Date(conversation.updatedAt), {
      addSuffix: true,
      locale: zhCN,
    }),
  }))

  useFocusEffect(
    useCallback(() => {
      conversationsStore.fetchConversations({
        last: conversationsStore.conversationsLast,
        size: 100,
      })
    }, []),
  )

  useEffect(() => {
    console.log("conversationsStore.conversations", conversationsStore.conversations)
    setConversations(conversationsStore.conversations)
  }, [conversationsStore.conversations])

  const handleConversationPress = (conversationId: string, agent?: string) => {
    if (__DEV__) {
      console.log(`Selected conversation: ${conversationId}`)
    }
    router.push(`/chat/${agent || "common"}/${conversationId}`)
  }

  const handleStartNewConversation = () => {
    if (__DEV__) {
      console.log("Create new conversation tapped")
      router.push("/chat/chat")
    }
  }

  const renderConversation: ListRenderItem<ConversationSummary> = ({ item }: any) => {
    const agent = agentsStore.modelsByName.get(item.model)
    return (
      <Pressable
        accessibilityRole="button"
        onPress={() => handleConversationPress(item.conversationId, item.model)}
        style={({ pressed }) => [
          // item.pinned && themed($conversationItemPinned),
          themed($conversationItem),
          pressed && themed($conversationItemPressed),
        ]}
      >
        <Image
          source={{
            uri:
              agent?.iconUrl ||
              "https://octopus-gpt.oss-cn-shanghai.aliyuncs.com/default_agent_icon.png",
          }}
          style={themed($agentIcon)}
        ></Image>
        <View style={themed($conversationContent)}>
          <View style={themed($itemHeader)}>
            <Text
              weight="medium"
              size="md"
              numberOfLines={1}
              style={themed($conversationTitle)}
              text={item.title}
            />

            {/*<View style={themed($headerRight)}>
          {item.pinned ? (
            <View style={themed($pinnedBadge)}>
              <Text size="xxs" weight="medium" style={themed($pinnedBadgeText)} text="置顶" />
            </View>
          ) : null}
          <Text size="xxs" style={themed($timestampText)} text={item.updatedAtLabel} />
        </View>*/}
          </View>

          {/* <Text
        size="xxs"
        numberOfLines={1}
        style={themed($participantsText)}
        text={item.participants.join(" · ")}
      />*/}

          <View style={themed($itemBody)}>
            <Text
              size="xs"
              numberOfLines={1}
              style={themed($lastMessage)}
              text={agent?.requestModalities.includes("image") ? "[图片消息]" : item.conversationId}
            />

            {/*{item.unreadCount ? (
          <View style={themed($unreadBadge)}>
            <Text
              size="xxs"
              weight="medium"
              style={themed($unreadBadgeText)}
              text={`${Math.min(item.unreadCount, 99)}`}
            />
          </View>
        ) : null}*/}
          </View>
        </View>
      </Pressable>
    )
  }

  const keyExtractor = (item: ConversationSummary) => item.conversationId

  const renderListHeader = () => (
    <View style={themed($headerContainer)}>
      <View style={themed($headerRow)}>
        <View style={$styles.flex1}>
          <Text weight="medium" size="lg" text="对话" />
          <Text size="xs" style={themed($subtitleText)} text="快速回到最近的 Octopus 对话" />
        </View>

        <Button
          preset="filled"
          text="新对话"
          onPress={handleStartNewConversation}
          style={themed($newConversationButton)}
          textStyle={themed($newConversationButtonText)}
        />
      </View>
    </View>
  )

  const ItemSeparatorComponent = () => <View style={themed($itemSeparator)} />

  return (
    <Screen
      preset="fixed"
      safeAreaEdges={["top"]}
      style={themed($screen)}
      contentContainerStyle={$styles.flex1}
    >
      <FlatList
        data={conversations}
        renderItem={renderConversation}
        keyExtractor={keyExtractor}
        contentContainerStyle={themed($listContent)}
        ListHeaderComponent={renderListHeader}
        ItemSeparatorComponent={ItemSeparatorComponent}
        showsVerticalScrollIndicator={false}
      />
    </Screen>
  )
}

const $screen: ThemedStyle<ViewStyle> = ({ colors }) => ({
  flex: 1,
  backgroundColor: colors.background,
})

const $listContent: ThemedStyle<ViewStyle> = ({ spacing }) => ({
  paddingHorizontal: spacing.lg,
  paddingBottom: spacing.xxl,
})

const $headerContainer: ThemedStyle<ViewStyle> = ({ spacing }) => ({
  paddingTop: spacing.lg,
  paddingBottom: spacing.md,
})

const $headerRow: ThemedStyle<ViewStyle> = ({ spacing }) => ({
  flexDirection: "row",
  alignItems: "center",
  justifyContent: "space-between",
  paddingRight: spacing.xxs,
})

const $subtitleText: ThemedStyle<TextStyle> = ({ colors }) => ({
  color: colors.textDim,
  marginTop: 4,
})

const $newConversationButton: ThemedStyle<ViewStyle> = ({ spacing }) => ({
  minHeight: 44,
  paddingHorizontal: spacing.md,
})

const $newConversationButtonText: ThemedStyle<TextStyle> = () => ({
  fontSize: 14,
})

const $itemSeparator: ThemedStyle<ViewStyle> = ({ spacing }) => ({
  height: spacing.sm,
})

const $conversationItem: ThemedStyle<ViewStyle> = ({ colors, spacing }) => ({
  borderRadius: spacing.md,
  borderWidth: 1,
  borderColor: colors.separator,
  backgroundColor: colors.palette.neutral100,
  paddingHorizontal: spacing.md,
  paddingVertical: spacing.sm,
  flexDirection: "row",
  alignItems: "center",
  gap: spacing.lg,
})

const $conversationContent: ThemedStyle<ViewStyle> = ({ colors, spacing }) => ({
  flex: 1,
})

const $agentIcon: ThemedStyle<ImageStyle> = () => ({
  width: 55,
  height: 55,
  borderRadius: 55,
})

const $conversationItemPinned: ThemedStyle<ViewStyle> = ({ colors }) => ({
  borderColor: colors.tint,
})

const $conversationItemPressed: ThemedStyle<ViewStyle> = ({ colors }) => ({
  backgroundColor: colors.palette.neutral200,
})

const $itemHeader: ThemedStyle<ViewStyle> = ({ spacing }) => ({
  flexDirection: "row",
  alignItems: "center",
  marginBottom: spacing.xs,
})

const $conversationTitle: ThemedStyle<TextStyle> = ({ colors }) => ({
  color: colors.text,
  flexShrink: 1,
})

const $headerRight: ThemedStyle<ViewStyle> = ({ spacing }) => ({
  flexDirection: "row",
  alignItems: "center",
  marginLeft: spacing.sm,
})

const $pinnedBadge: ThemedStyle<ViewStyle> = ({ colors, spacing }) => ({
  paddingHorizontal: spacing.xs,
  paddingVertical: spacing.xxs,
  borderRadius: spacing.xs,
  backgroundColor: colors.palette.primary100,
})

const $pinnedBadgeText: ThemedStyle<TextStyle> = ({ colors }) => ({
  color: colors.tint,
})

const $timestampText: ThemedStyle<TextStyle> = ({ colors, spacing }) => ({
  color: colors.textDim,
  marginLeft: spacing.xs,
})

const $participantsText: ThemedStyle<TextStyle> = ({ colors, spacing }) => ({
  color: colors.textDim,
  marginBottom: spacing.xs,
})

const $itemBody: ThemedStyle<ViewStyle> = () => ({
  flexDirection: "row",
  alignItems: "center",
})

const $lastMessage: ThemedStyle<TextStyle> = ({ colors }) => ({
  color: colors.textDim,
  flex: 1,
})

const $unreadBadge: ThemedStyle<ViewStyle> = ({ colors, spacing }) => ({
  minWidth: 24,
  height: 24,
  borderRadius: 12,
  paddingHorizontal: spacing.xs,
  justifyContent: "center",
  alignItems: "center",
  backgroundColor: colors.tint,
  marginLeft: spacing.xs,
})

const $unreadBadgeText: ThemedStyle<TextStyle> = ({ colors }) => ({
  color: colors.palette.neutral100,
})

export default ConversationsPage
